package com.axx.android.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

/**
 * Created by sunjie on 2017/6/14.
 */

public class ImageUtils {
    private static final int[] DEFAULT_SIZE = {860, 480}; //默认图片宽高
    public static final int DEFAULT_IMAGE_SIZE = 100;
    public static final int DEFAULT_HEADER_SIZE = 20;



    public static byte[] compressBitmap(String path,int imageSize) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(path, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        double hh = DEFAULT_SIZE[0];
        double ww = DEFAULT_SIZE[1];
        int be = 1;
        if (w > h && w > ww) {
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;
        newOpts.inTempStorage = new byte[100 * 1024];
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(path);
            bitmap = BitmapFactory.decodeStream(fileInputStream, null, newOpts);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return bitmap2byte(bitmap,imageSize);
    }
    /**
     * @param photo
     * @return 将图片压缩到指定大小
     */
    public static byte[] bitmap2byte(Bitmap photo,int imageSize) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int quality = 95;
        photo.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        while (baos.toByteArray().length / 1024 > imageSize) {
            baos.reset();
            photo.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            quality -= 5;
        }
        byte[] images = baos.toByteArray();
        if (!photo.isRecycled()) {
            photo.recycle();
            System.gc();
        }
        return images;
    }


    public static Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(
                drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                        : Bitmap.Config.RGB_565);

        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;

    }


}
